<template>
  <div
    ref="selectDropdownRef"
    :class="['toolbar-select-dropdown', { 'is-filterable': filterable }]"
    :style="[selectFloatingStyles, { minWidth: selectWidth }]"
  >
    <!-- 搜索框 -->
    <input
      v-if="filterable"
      ref="filterInputRef"
      v-model="filterText"
      type="text"
      class="toolbar-select-filter"
      :placeholder="placeholder"
      @input="handleFilterInput"
      @keydown.esc.stop="handleEsc"
      @keydown.enter.stop="handleEnter"
      @keydown.down.stop.prevent="navigateOptions('next')"
      @keydown.up.stop.prevent="navigateOptions('prev')"
    />

    <!-- 选项列表 -->
    <div class="toolbar-select-options">
      <slot />
      <div
        v-if="!hasOptions"
        class="toolbar-select-option toolbar-select-empty"
      >
        <slot name="empty"> 暂无数据 </slot>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, inject, ref, watch } from "vue";
import { selectKey } from "./token";

const props = defineProps<{
  filterable?: boolean;
  placeholder?: string;
  selectWidth?: string;
  selectFloatingStyles?: any;
}>();

const select = inject(selectKey)!;
const filterInputRef = ref<HTMLInputElement | null>(null);
const selectDropdownRef = ref<HTMLElement | null>(null);
const filterText = ref("");

const hasOptions = computed(() => {
  return select.optionsArray.length > 0;
});

const handleFilterInput = () => {
  select.state.inputValue = filterText.value;
  // 更新选项可见性
  select.optionsArray.forEach((option) => {
    if (option.updateOption) {
      option.updateOption(filterText.value);
    }
  });
};

const handleEsc = () => {
  select.state.expanded = false;
};

const handleEnter = () => {
  const hoverIndex = select.state.hoveringIndex;
  if (hoverIndex >= 0 && hoverIndex < select.optionsArray.length) {
    const option = select.optionsArray[hoverIndex];
    if (option && !option.isDisabled) {
      select.handleOptionSelect(option);
    }
  }
};

const navigateOptions = (direction: "next" | "prev") => {
  const options = select.optionsArray.filter((opt) => opt.visible !== false);
  if (options.length === 0) return;

  let newIndex = select.state.hoveringIndex;
  if (direction === "next") {
    newIndex++;
    if (newIndex >= options.length) {
      newIndex = 0;
    }
  } else {
    newIndex--;
    if (newIndex < 0) {
      newIndex = options.length - 1;
    }
  }

  // 跳过禁用的选项
  let attempts = 0;
  while (attempts < options.length && options[newIndex]?.isDisabled) {
    if (direction === "next") {
      newIndex = (newIndex + 1) % options.length;
    } else {
      newIndex = (newIndex - 1 + options.length) % options.length;
    }
    attempts++;
  }

  select.state.hoveringIndex = newIndex;
};

watch(
  () => select.state.expanded,
  (expanded) => {
    if (expanded && props.filterable && filterInputRef.value) {
      nextTick(() => {
        filterInputRef.value?.focus();
      });
    } else {
      filterText.value = "";
      select.state.inputValue = "";
    }
  },
  { immediate: true }
);

defineExpose({
  filterInputRef,
  selectDropdownRef,
});
</script>

<style scoped lang="scss">
.toolbar-select-dropdown {
  position: absolute;
  z-index: 2000;
  background: var(--editor-color-white);
  border: 1px solid var(--editor-border-color-light);
  border-radius: var(--editor-radius-medium);
  box-shadow: var(--editor-shadow);
  max-height: 300px;
  min-width: var(--toolbar-select-dropdown-min-width);
  overflow: hidden;
}

.toolbar-select-filter {
  width: 100%;
  padding: 8px 12px;
  border: none;
  border-bottom: 1px solid var(--editor-border-color-light);
  outline: none;
  font-size: var(--editor-font-size);
  color: var(--editor-text-color);
  background: transparent;
}

.toolbar-select-options {
  max-height: 250px;
  overflow-y: auto;

  scrollbar-width: thin;
  scrollbar-color: var(--editor-scrollbar-thumb-color) transparent;

  &::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }

  &::-webkit-scrollbar-track {
    width: 8px;
    background: transparent;
  }

  &:hover::-webkit-scrollbar-thumb {
    background-color: var(--editor-scrollbar-thumb-color);
    background-clip: padding-box;
    border-radius: 4px;
    transition: background-color 0.3s;
    cursor: pointer;
  }

  &::-webkit-scrollbar-thumb:hover {
    background-color: var(--editor-scrollbar-thumb-hover-color);
  }
}

.toolbar-select-empty {
  text-align: center;
  color: var(--editor-text-color-light);
  padding: 20px;
}
</style>
